package com.gxg.services;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SftpService
{
  @Value("${sftp.session.timeout}")
  private int sessionTimeout;
  
  public String uploadFile(String destinationDirectory, String sourceDirectory, String fileName, String username, String password, String host, int port)
  {
    FileInputStream in = null;
    ChannelSftp sftp = null;
    Session sshSession = null;
    Channel channel;
    try
    {
      JSch jSch = new JSch();
      sshSession = jSch.getSession(username, host, port);
      sshSession.setPassword(password);
      Properties sshConfig = new Properties();
      sshConfig.put("StrictHostKeyChecking", "no");
      sshSession.setConfig(sshConfig);
      sshSession.setTimeout(this.sessionTimeout);
      sshSession.connect();
      channel = sshSession.openChannel("sftp");
      channel.connect();
      sftp = (ChannelSftp)channel;
    }
    catch (Exception e)
    {
      return "连接sftp时出错：" + e.getMessage();
    }
    if (sftp == null) {
      return "连接sftp时出错！";
    }
    try
    {
      Vector content = sftp.ls(destinationDirectory);
      if (content == null) {
        sftp.mkdir(destinationDirectory);
      }
      sftp.cd(destinationDirectory);
    }
    catch (SftpException e)
    {
      try
      {
        sftp.mkdir(destinationDirectory);
        sftp.cd(destinationDirectory);
      }
      catch (SftpException e1)
      {
        return "ftp创建文件路径失败！路径为：" + destinationDirectory;
      }
    }
    File file = new File(sourceDirectory);
    try
    {
      in = new FileInputStream(file);
      sftp.put(in, fileName);
    }
    catch (FileNotFoundException e)
    {
      return "文件不存在：" + sourceDirectory;
    }
    catch (SftpException e)
    {
      return "sftp异常：" + e.getMessage();
    }
    finally
    {
      if (in != null) {
        try
        {
          in.close();
        }
        catch (IOException e)
        {
          return "关闭文件流出错：" + e.getMessage();
        }
      }
      if ((sftp != null) && 
        (sftp.isConnected())) {
        sftp.disconnect();
      }
      if ((sshSession != null) && 
        (sshSession.isConnected()))
      {
        sshSession.disconnect();
        sshSession = null;
      }
    }
    return "ok";
  }
}
